/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年9月21日
 * @version 0.1
 */
package com.suredy.resource.ctrl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.mvc.model.MessageModel;
import com.suredy.resource.entity.ResourceEntity;
import com.suredy.resource.entity.SegmentEntity;
import com.suredy.resource.model.Resource;
import com.suredy.resource.model.ResourceType;
import com.suredy.resource.model.Segment;
import com.suredy.resource.service.ResourceSrv;
import com.suredy.resource.service.SegmentSrv;
import com.suredy.security.model.User;
import com.suredy.security.service.UserSrv;

/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value = "/config")
public class SegmentCtrl extends BaseCtrl {

	private final static Logger log = LoggerFactory.getLogger(SegmentCtrl.class);

	@Autowired
	private SegmentSrv segmentSrv;

	@Autowired
	ResourceSrv resourceSrv;

	@Autowired
	private UserSrv userSrv;

	@RequestMapping({"segment/user"})
	@ResponseBody
	public Object UserSegments(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute(Constants.SESSION_LOGIN_USER);
		// not login
		if (user == null) {
			log.info("Session timeout or User didn't login.");
			return MessageModel.createErrorMessage("用户未登录或会话超时", null);
		}
		// 当前用户可访问的安全资源点
		List<String> userSecurityResources = this.userSrv.getPermissions(user.getUniqueCode());
		// TODO 读取数据库内的资源配置或者从Session读取，二选一
		// Set<String> permissions = this.userSrv.getPermissions(user.getUniqueCode());
		// 全部页面片段相关的安全资源点
		List<Resource> segments = this.resourceSrv.getAll(ResourceType.Segment);
		// 已授权用户访问的菜单相关安全资源点
		List<String> allowedResources = new ArrayList<String>();
		for (Resource segment : segments) {
			if (userSecurityResources.contains(segment.getUri())) {
				allowedResources.add(segment.getUri());
			}
		}
		return allowedResources;
	}


	@RequestMapping(value = "segment/manager")
	public ModelAndView manager() {
		ModelAndView view = new ModelAndView("/config/resource/segment-manager");
		List<Segment> data = this.segmentSrv.getAll();
		view.addObject("data", data);
		return view;
	}

	@RequestMapping(value = "segment/create")
	public ModelAndView crete() {
		ModelAndView view = new ModelAndView("/config/resource/segment-create");
		return view;
	}

	@RequestMapping("segment/create-save")
	@ResponseBody
	public Object doCreate(HttpServletRequest request) {
		String name = request.getParameter("name");
		String uri = request.getParameter("uri");
		String sort = request.getParameter("sort");

		if (StringUtils.isBlank(name) || StringUtils.isBlank(uri)) {
			log.info("Parameter String[name|uri] is blank.");
			return MessageModel.createErrorMessage("参数不足, 名称和资源标识必须填写", null);
		}

		Date date = new Date();
		ResourceEntity resource = new ResourceEntity();
		resource.setCreateTime(date);
		resource.setLastModifiedTime(date);
		resource.setName(name);
		resource.setType(ResourceType.Segment.getType());
		resource.setUri(uri);

		SegmentEntity menu = new SegmentEntity();
		menu.setUri(uri);
		menu.setName(name);
		menu.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		menu.setResource(resource);
		this.segmentSrv.save(menu);

		return MessageModel.createSuccessMessage(null, null);
	}

	@RequestMapping(value = "segment/edit")
	public ModelAndView edit(String segmentId) {
		ModelAndView view = new ModelAndView("/config/resource/segment-edit");
		if (StringUtils.isBlank(segmentId)) {
			log.info("Parameter String[segmentId] is blank.");
			return view;
		}
		Segment data = this.segmentSrv.getById(segmentId);
		view.addObject("data", data);
		view.addObject("id", segmentId);
		return view;
	}

	@RequestMapping("segment/edit-save")
	@ResponseBody
	public Object doEdit(HttpServletRequest request) {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String uri = request.getParameter("uri");
		String sort = request.getParameter("sort");

		if (StringUtils.isBlank(name) || StringUtils.isBlank(uri)) {
			log.info("Parameter String[name|uri] is blank.");
			return MessageModel.createErrorMessage("参数不足, 名称和资源标识必须填写", null);
		}

		SegmentEntity menu = this.segmentSrv.get(id);
		if (menu == null) {
			return MessageModel.createErrorMessage("参数错误, 未找到与ID对应的资源信息", null);
		}

		menu.setUri(uri);
		menu.setName(name);
		menu.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));

		this.segmentSrv.update(menu);

		return MessageModel.createSuccessMessage(null, null);
	}

	@RequestMapping("segment/delete")
	@ResponseBody
	public Object doDelete(String segmentId) {
		if (StringUtils.isBlank(segmentId)) {
			return MessageModel.createErrorMessage("无效的资源ID！", null);
		}

		SegmentEntity menu = this.segmentSrv.get(segmentId);

		if (menu == null) {
			return MessageModel.createErrorMessage("未找到与ID对应的资源信息！", null);
		}

		try {
			this.segmentSrv.delete(menu);
		} catch (Exception e) {
			return MessageModel.createErrorMessage("删除不成功,控制资源信息映射错误！", null);
		}

		return MessageModel.createSuccessMessage(null, null);
	}

}
